package com.zzyl.intercept;

import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (token == null || token == ""){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        else {
            try {
                //有token，解析token
                Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
                if (claims == null || claims.isEmpty()){
                    throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
                }
                Integer id = (Integer) claims.get("id");
                UserThreadLocal.set(Long.valueOf(id));
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(BasicEnum.LOGIN_FAIL);
            }

        }
        return true;
    }


}
